package com.yyj.util;

import java.io.*;

/**
 * 数据流处理工具类
 * 
 * @author Luozhh
 * @e-mail luozhh1216@foxmail.com
 * @datetime 2012-7-12 上午10:54:17
 */
public class StreamUtil {

	private StreamUtil() {
	}

	/**
	 * 获取文件的字节数据
	 * 
	 * @param file
	 *            文件对象
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	public static byte[] getFileData(File file) throws IOException {
		return readInStream(new FileInputStream(file));
	}

	public static void writeFile(File saveFile, byte[] fileData) throws IOException {
		FileOutputStream outStream = new FileOutputStream(saveFile);
		outStream.write(fileData);
		outStream.close();
	}

	/**
	 * 从输入流中读取字节数据
	 * 
	 * @param inStream
	 * @return
	 * @throws IOException
	 */
	public static byte[] readInStream(InputStream inStream) throws IOException {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		return data;
	}

	/**
	 * 从输入流中读取字节写到输出流
	 * 
	 * @param inStream
	 * @param outStream
	 * @throws IOException
	 */
	public static void copy(InputStream inStream, OutputStream outStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		outStream.close();
		inStream.close();
	}
}
